/**
 * 系统用户管理
 * @authors supmain (mtingfeng@gmail.com)
 * @date    2015-01-27 09:34:53
 * @for 系统用户管理.html
 * @version $1.0$
 */
var BSTMG = BSTMG || {};
BSTMG.sysUserManager = {
	init: function(){
		var that = this;
		/* 全选 */
		that.checkAll();
		/* 新增 */
		that.userManager();
	},
	checkAll: function(){
		var $table = $("#userTable"),
			$thead = $table.find("thead"),
			$tbody = $table.find("tbody");
		// 全选
		$thead.on("click",".simple",function(){
			var $this = $(this),
				$parent = $this.parents('table.table'),
				$checkbox = $parent.find('input[type=checkbox]').not($this);
			$this.prop("checked") ? $checkbox.prop("checked",true) : $checkbox.prop("checked",false) ;
		});
		$tbody.on("click","input[type=checkbox]",function(){
			var $this = $(this),
				$all = $this.parents("tbody").eq(0).find("input[type=checkbox]"),
				$checkbox = $all.not($this).filter(":checked");
			var $checkall = $this.parents('table.table').find("thead input.simple");
			( $this.prop("checked") && ($checkbox.length + 1) == $all.length ) ? $checkall.prop("checked",true) : $checkall.prop("checked",false) ;
		});
	},
	userManager: function(){
		var $table = $("#userTable"),
			$thead = $table.find("thead"),
			$tbody = $table.find("tbody");
		var $operator = $(".operator");
		$operator.on("click",".addnew",function(){
			addLookEditUser( { title: "添加用户" } );
		}).on("click",".delete",function(){
			var array = [];
			$tbody.find("input[type=checkbox]:checked").each(function(){
				var $this = $(this),
					id = $.trim( $this.attr( "data-id" ) );
				array.push( id );
			});
			if( array.length ){
				BSTYUN.dialog.confirm("确定要删除吗？",function(){
					deleteUser( array );
				});
			}else{
				BSTYUN.dialog.warn("请选择一条数据！");
			};
		}).on("click",".resetpsd",function(){
			var array = [];
			$tbody.find("input[type=checkbox]:checked").each(function(){
				var $this = $(this),
					id = $.trim( $this.attr( "data-id" ) );
				array.push( id );
			});
			if( array.length ){
				BSTYUN.dialog.confirm("确定要重置密码吗？重置后的密码为“11111111”！",function(){
					resetPsd( array );
				});
			}else{
				BSTYUN.dialog.warn("请选择一条数据！");
			};
		});
		$tbody.on("click",".look",function(){
			var $this = $(this),
				$checkbox = $this.parent().parent().find("td:first-child input"),
				id = $.trim( $checkbox.attr("data-id") );
			addLookEditUser( { id: id , title: "查看用户" , look: true } );
		}).on("click",".edit",function(){
			var $this = $(this),
				$checkbox = $this.parent().parent().find("td:first-child input"),
				id = $.trim( $checkbox.attr("data-id") );
			addLookEditUser( { id: id , title: "编辑用户" , edit: true } );
		}).on("click",".delete",function(){
			var $this = $(this),
				$checkbox = $this.parent().parent().find("td:first-child input"),
				id = $.trim( $checkbox.attr("data-id") );
			BSTYUN.dialog.confirm("确定要删除吗？",function(){
				deleteUser( [id] );
			});
		});
		// 新增  查看 编辑 删除
		function addLookEditUser( params ){
			var dialog = null,
				//html = '<div id="adduser"><form class="form-horizontal" role="form"><div class="form-group"><label for="no" class="col-sm-3 control-label">用户编号：</label><div class="col-sm-8"><input type="text" class="form-control" id="no" placeholder="用户编号"></div></div><div class="form-group"><label for="name" class="col-sm-3 control-label">用户名：</label><div class="col-sm-8"><input type="text" class="form-control" id="name" placeholder="用户名"></div></div><div class="form-group"><label for="role" class="col-sm-3 control-label">角色：</label><div class="col-sm-8"><select class="form-control input-sm" id="role"><option value="0">管理员</option><option value="1">普通</option></select></div></div><div class="form-group"><label for="psd" class="col-sm-3 control-label">密码：</label><div class="col-sm-8"><input type="text" class="form-control" id="psd" placeholder="密码"></div></div><div class="form-group"><label for="note" class="col-sm-3 control-label">备注：</label><div class="col-sm-8"><textarea id="note"></textarea></div></div></form></div>';
				html = '<div id="adduser"><input type="hidden" id="adminId"/><form class="form-horizontal" role="form"><div class="form-group"><label for="no" class="col-sm-3 control-label">用户编号：</label><div class="col-sm-8"><input type="text" class="form-control" id="no" placeholder="用户编号"></div></div><div class="form-group"><label for="rolename" class="col-sm-3 control-label">用户名：</label><div class="col-sm-8"><input type="text" class="form-control" autocomplete="off" id="rolename" placeholder="用户名"></div></div>';
				html +=	'<div class="form-group"><label for="role" class="col-sm-3 control-label">角色：</label><div class="col-sm-8">';
				html +=	'<select class="form-control input-sm" id="role">';
				$.ajax({
	 				url: '/sysAdmin/sysUserManager/findRoles',
	 				type: 'post',
	 				async : false,
	 				dataType: 'json',
	 				success: function( data ){
	 					$.each(data.roles,function(index,role){
	 						if(role.staticDataCode=="PUBLISHER"){
	 							html +=	'<option value="'+role.staticDataCode+'" selected="selected">'+role.staticDataName+'</option>';
	 						}else{
	 							html +=	'<option value="'+role.staticDataCode+'">'+role.staticDataName+'</option>';
	 						}
	 					})
	 				},
	 				error: function(error){
	 					BSTYUN.dialog.warn("网络异常，请联系管理员！");
	 				}
				});
				html += '</select></div></div><div class="form-group">';
				if(params.title == '添加用户') {
					html += '<label for="psd" class="col-sm-3 control-label">密码：</label><div class="col-sm-8"><input type="password" class="form-control" id="psd" placeholder="密码" value="11111111"></div>';
				}
				html += '</div><div class="form-group"><label for="note" class="col-sm-3 control-label">备注：</label><div class="col-sm-8"><textarea id="note"></textarea></div></div></form></div>';	
				_getData = null;
			dialog = BSTYUN.dialog.creat({
				id : "adduser",
				title: params.title,
				content : html,
				init: initDialog,
				width: 450
			});
			if(params.title != '查看用户') {
				dialog.button(
					{
						name : "保存",
						callback : confirm
					},{
						name : "取消"
					}
				);
			}
			function initDialog(){
				var $content = this.DOM.content,
					$adminId = $content.find("#adminId"),
					$no = $content.find("#no"),
					$rolename = $content.find("#rolename"),
					$role = $content.find("#role"),
					$psd = $content.find("#psd"),
					$note = $content.find("#note");
				if( params.id ){ // 有ID，编辑和查看 ajax填充内容
					$.ajax({
		 				url: '/sysAdmin/sysUserManager/findSysUser',
		 				type: 'post',
		 				dataType: 'json',
		 				data: {id: params.id } ,
		 				success: function( data ){
		 					var admin = data.admin;
		 					$adminId.val( admin.adminId );
		 					$no.val( admin.adminNum );
		 					$rolename.val( admin.adminName );
		 					$role.val( admin.roleId );
		 					$psd.val( admin.adminPassword );
		 					$note.val( admin.remark );
		 				},
		 				error: function(error){
		 					BSTYUN.dialog.warn("网络异常，请联系管理员！");
		 				}
		 			});
				};
				// 获取数据函数
				function getData(){
					return {
						adminId :$.trim( $adminId.val() ),
						no: $.trim( $no.val() ),
						rolename : $.trim( $rolename.val() ),
						role: $.trim( $role.val() ),
						psd: $.trim( $psd.val() ),
						note: $.trim( $note.val() )
					};
				};
				_getData = getData;
			};
			// 确定
			function confirm(){
				if( params.look ) return true; // 查看用户,不能保存
				var $content = this.DOM.content,
					data = _getData();
				if( data.no == "" ){
					BSTYUN.dialog.warn("用户编号不能为空！");
					return false;
				};
				if( (!/^[1-9][0-9]*$/.test( data.no )) ||  (data.no > 1000) ){
					BSTYUN.dialog.warn("用户编号只能为1-1000范围的整数！");
					return false;
				};
				if( data.rolename == "" ){
					BSTYUN.dialog.warn("用户名不能为空！");
					return false;
				};
//				if( data.psd == "" ){
//					BSTYUN.dialog.warn("密码不能为空！");
//					return false;
//				};
				// edit = true 编辑模式 ; undefined 说明是新增模式，insert
				params.edit ? data["edit"] = true : data["edit"] = false ;
				sendAjaxRequest( data );
			};
		};
		// 新增 编辑 ajax请求
		function sendAjaxRequest( _data ){
			$.ajax({
 				url: '/sysAdmin/operate/sysUserManager/addOrUpdateSysUser',
 				type: 'post',
 				dataType: 'json',
 				data:{
 					adminId : _getData().adminId,
 					adminNum : _getData().no,
					adminName : _getData().rolename,
					roleId : _getData().role,
					adminPassword : _getData().psd,
					remark : _getData().note
 				},
 				beforeSend: function(){},
 				complete: function(){},
 				success: function( data ){
 					location.href = "/sysAdmin/sysUserManager";
 					
// 					if( _data.isNew ){
// 						 新增
// 						var dataid = data.adminId,
// 						html = '<tr><td><input type="checkbox" class="simple" data-id="'+ dataid +'"></td><td>'+ _data.no +'</td><td>'+ _data.name +'</td><td>'+ _data.note +'</td><td><a type="button" class="btn btn-default look">查看</a> <a type="button" class="btn btn-default edit">编辑</a><a type="button" class="btn btn-default delete">删除</a></td></tr>';
// 						$tbody.append( html );
// 					}else{
// 						// 编辑
// 						$tbody.find("tr").each(function(index,val){
// 							
// 						});
// 					};
 				},
 				error: function(error){
 					BSTYUN.dialog.warn("网络异常，请联系管理员！");
 				}
 			});
		};
		// 删除用户
		function deleteUser( array,flag){
			$.ajax({
 				url: '/sysAdmin/operate/sysUserManager/delOrResetSysUser?array='+array,
 				type: 'post',
 				dataType: 'json',
 				data:{
 					flag :0
 				},
 				beforeSend: function(){},
 				complete: function(){},
 				success: function( data ){
 					if(data.isSuccess) {
 						//BSTYUN.dialog.warn(data.message);
 						location.href = "/sysAdmin/sysUserManager";
 					}else {
 						BSTYUN.dialog.warn(data.message);
 					}
// 					if( !data.isSuccess ){BSTYUN.dialog.warn("删除失败！");return;};
// 					$tbody.find("input[type=checkbox]").each(function(){
// 						var $this = $(this),
// 							id = $.trim( $this.attr( "data-id" ) );
// 						if( array.indexOf( id ) >= 0 ){
// 							$this.parent().parent().remove();
// 						};
// 					});
 				},
 				error: function(error){
 					BSTYUN.dialog.warn("网络异常，请联系管理员！");
 				}
 			});
		};
		// 重置密码
		function resetPsd( array,flag ){
			$.ajax({
				url: '/sysAdmin/operate/sysUserManager/delOrResetSysUser?array='+array,
 				type: 'post',
 				dataType: 'json',
 				//data: array.join(",") ,
 				data:{
 					flag :1
 				},
 				beforeSend: function(){},
 				complete: function(){},
 				success: function( data ){
 					if(data.isSuccess) {
 						BSTYUN.dialog.ok("重置密码成功！",function(){
 							location.href = "/sysAdmin/sysUserManager";
						});
 					}else {
 						BSTYUN.dialog.warn(data.message);
 					}
 				},
 				error: function(error){
 					BSTYUN.dialog.warn("网络异常，请联系管理员！");
 				}
 			});
		};
	}
};
$(function(){
	BSTMG.sysUserManager.init();
});